<script setup>
import {ref, onBeforeUnmount, watch, computed} from 'vue';
import {GitBranch, Clock, Trophy, Star, CheckCircle, XCircle, RotateCcw} from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const COLORS = ['red', 'blue', 'green', 'yellow'];
const SHAPES = ['circle', 'triangle', 'square', 'star'];
const NUMBERS = [1, 2, 3, 4];

const COLOR_CLASSES = {
  red: 'bg-red-500',
  blue: 'bg-blue-500',
  green: 'bg-green-500',
  yellow: 'bg-yellow-500'
};

const TARGET_CARD = {
  id: -1,
  color: 'red',
  shape: 'triangle',
  number: 2
};

const TRIALS_TO_COMPLETE = 128;
const CONSECUTIVE_FOR_RULE_CHANGE = 10;

const emit = defineEmits(['complete']);

const stage = ref('instructions');
const currentTrialIndex = ref(0);
const currentRule = ref('color');
const trials = ref([]);
const responses = ref([]);
const reactionTimes = ref([]);
const timeLeft = ref(720); // 12分钟
const startTime = ref(0);
const trialStartTime = ref(0);
const score = ref(0);
const ruleChanges = ref([]);
const consecutiveCorrect = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);
const completedCategories = ref([]);

let timerInterval = null;

const generateCard = () => ({
  id: Math.random(),
  color: COLORS[Math.floor(Math.random() * COLORS.length)],
  shape: SHAPES[Math.floor(Math.random() * SHAPES.length)],
  number: NUMBERS[Math.floor(Math.random() * NUMBERS.length)]
});

const generateTrial = (rule) => {
  const cards = [];
  let correctCardIndex = Math.floor(Math.random() * 4);

  for (let i = 0; i < 4; i++) {
    let card = generateCard();

    if (i === correctCardIndex) {
      card[rule] = TARGET_CARD[rule];
    } else {
      while (card[rule] === TARGET_CARD[rule]) {
        card = generateCard();
      }
    }
    cards.push(card);
  }

  return {
    id: currentTrialIndex.value,
    cards,
    correctRule: rule,
    correctCard: correctCardIndex
  };
};

const handleStartTest = () => {
  stage.value = 'test';
  startTime.value = Date.now();
};

const handleCardSelect = (cardIndex) => {
  const reactionTime = Date.now() - trialStartTime.value;
  const correct = cardIndex === trials.value[0].correctCard;

  responses.value.push(cardIndex);
  reactionTimes.value.push(reactionTime);

  if (correct) {
    score.value++;
    consecutiveCorrect.value++;
    if (consecutiveCorrect.value >= CONSECUTIVE_FOR_RULE_CHANGE) {
      changeRule();
    }
  } else {
    consecutiveCorrect.value = 0;
  }

  feedbackCorrect.value = correct;
  showFeedback.value = true;

  setTimeout(() => {
    showFeedback.value = false;
    if (currentTrialIndex.value < TRIALS_TO_COMPLETE - 1) {
      currentTrialIndex.value++;
    } else {
      stage.value = 'results';
    }
  }, 1000);
};

const changeRule = () => {
  const availableRules = ['color', 'shape', 'number'].filter(rule =>
    !completedCategories.value.includes(rule) && rule !== currentRule.value
  );

  if (availableRules.length > 0) {
    const newRule = availableRules[Math.floor(Math.random() * availableRules.length)];
    completedCategories.value.push(currentRule.value);
    currentRule.value = newRule;
    ruleChanges.value.push(currentTrialIndex.value);
    consecutiveCorrect.value = 0;
  }
};

const getRuleAtTrial = (trialIndex) => {
  let ruleForTrial = 'color';
  let ruleIdx = 0;
  const rules = ['color', 'shape', 'number'];
  for (const changePoint of ruleChanges.value) {
    if (trialIndex >= changePoint) {
      ruleIdx = (ruleIdx + 1) % rules.length;
      ruleForTrial = rules[ruleIdx];
    }
  }
  return ruleForTrial;
};

const calculatePerseverativeErrors = () => {
  let errors = 0;
  ruleChanges.value.forEach((changePoint, index) => {
    const previousRule = index === 0 ? 'color' : getRuleAtTrial(ruleChanges.value[index - 1]);
    for (let i = 0; i < 5 && changePoint + i < responses.value.length; i++) {
      const trialIndex = changePoint + i;
      const responseCardIndex = responses.value[trialIndex];
      const currentRuleForTrial = getRuleAtTrial(trialIndex);
      const isCorrectNow = trials.value[0].cards[responseCardIndex][currentRuleForTrial] === TARGET_CARD[currentRuleForTrial];
      const wouldHaveBeenCorrect = trials.value[0].cards[responseCardIndex][previousRule] === TARGET_CARD[previousRule];

      if (!isCorrectNow && wouldHaveBeenCorrect) {
        errors++;
      }
    }
  });
  return errors;
};

const handleComplete = () => {
  const totalTrials = responses.value.length;
  const totalCorrect = score.value;
  const overallAccuracy = totalTrials > 0 ? Math.round((totalCorrect / totalTrials) * 100) : 0;
  const averageReactionTime = reactionTimes.value.length > 0 ? Math.round(reactionTimes.value.reduce((sum, rt) => sum + rt, 0) / reactionTimes.value.length) : 0;

  const ruleChangeSuccess = ruleChanges.value.length;
  const perseverativeErrors = calculatePerseverativeErrors();

  const flexibilityScore = Math.min(30, ruleChangeSuccess * 10);
  const accuracyScore = Math.min(50, overallAccuracy * 0.5);
  const speedScore = Math.max(0, 20 - (averageReactionTime / 100));
  const finalScore = Math.round(flexibilityScore + accuracyScore + speedScore);

  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);

  const result = {
    id: Date.now().toString(),
    testType: 'concept-formation',
    score: finalScore,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalTrials,
      totalCorrect,
      overallAccuracy,
      averageReactionTime,
      ruleChanges: ruleChangeSuccess,
      categoriesCompleted: completedCategories.value.length,
      perseverativeErrors,
      conceptualFlexibility: Math.round((ruleChangeSuccess / 3) * 100),
      adaptabilityIndex: Math.round(100 - (perseverativeErrors / totalTrials) * 100),
      totalScore: score.value
    }
  };

  emit('complete', result);
};

watch(stage, (newStage) => {
  if (newStage === 'test' && timeLeft.value > 0) {
    timerInterval = setInterval(() => {
      timeLeft.value--;
      if (timeLeft.value <= 0) {
        clearInterval(timerInterval);
        stage.value = 'results';
      }
    }, 1000);
  } else {
    clearInterval(timerInterval);
  }
});

watch([currentTrialIndex, stage], () => {
  if (stage.value === 'test') {
    trials.value = [generateTrial(currentRule.value)];
    trialStartTime.value = Date.now();
  }
}, {immediate: true});

onBeforeUnmount(() => {
  clearInterval(timerInterval);
});

const progress = computed(() => (currentTrialIndex.value / TRIALS_TO_COMPLETE) * 100);

const finalResult = computed(() => {
  const totalTrials = responses.value.length;
  const totalCorrect = score.value;
  const overallAccuracy = totalTrials > 0 ? Math.round((totalCorrect / totalTrials) * 100) : 0;
  const ruleChangeSuccess = ruleChanges.value.length;
  const perseverativeErrors = calculatePerseverativeErrors();
  const averageReactionTime = reactionTimes.value.length > 0 ? Math.round(reactionTimes.value.reduce((sum, rt) => sum + rt, 0) / reactionTimes.value.length) : 0;

  const flexibilityScore = Math.min(30, ruleChangeSuccess * 10);
  const accuracyScore = Math.min(50, overallAccuracy * 0.5);
  const speedScore = Math.max(0, 20 - (averageReactionTime / 100));
  const finalScore = Math.round(flexibilityScore + accuracyScore + speedScore);

  return {finalScore, ruleChangeSuccess, overallAccuracy, perseverativeErrors, totalTrials};
});

const getShape = (shape, color) => {
  const shapeClass = `w-6 h-6 ${COLOR_CLASSES[color]}`;
  switch (shape) {
    case 'circle':
      return `<div class="${shapeClass} rounded-full"></div>`;
    case 'triangle':
      return `<div class="${shapeClass}" style="clip-path: polygon(50% 0%, 0% 100%, 100% 100%)"></div>`;
    case 'square':
      return `<div class="${shapeClass} rounded-sm"></div>`;
    case 'star':
      return `<div class="${shapeClass} rounded-sm transform rotate-45"></div>`;
    default:
      return `<div class="${shapeClass} rounded-full"></div>`;
  }
}

</script>

<template>
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-violet-200 shadow-lg">
      <CardHeader class="text-center pb-8">
        <div
          class="w-16 h-16 bg-gradient-to-br from-violet-700 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
          <GitBranch class="w-8 h-8 text-white"/>
        </div>
        <CardTitle class="text-2xl text-slate-800">{{ t('conceptFormation.title') }}</CardTitle>
        <p class="text-slate-600 mt-2">{{ t('conceptFormation.description') }}</p>
      </CardHeader>

      <CardContent class="space-y-6">
        <div class="bg-gradient-to-r from-violet-50 to-purple-50 rounded-xl p-6 border border-violet-100">
          <h3 class="font-semibold text-violet-900 mb-4 flex items-center gap-2">
            <Star class="w-5 h-5"/>
            {{ t('conceptFormation.instructionsTitle') }}
          </h3>
          <div class="space-y-3 text-slate-700">
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
              <p>{{ t('conceptFormation.instruction1') }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
              <p>{{ t('conceptFormation.instruction2') }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
              <p>{{ t('conceptFormation.instruction3') }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
              <p>{{ t('conceptFormation.instruction4') }}</p>
            </div>
          </div>
        </div>

        <div class="bg-slate-50 rounded-xl p-4 border border-slate-200">
          <h4 class="font-semibold text-slate-700 mb-3 text-center">{{ t('conceptFormation.exampleTitle') }}</h4>
          <div class="flex items-center justify-center gap-6">
            <div class="text-center">
              <div class="text-sm text-slate-600 mb-2">{{ t('conceptFormation.targetCard') }}</div>
              <div
                class="w-20 h-20 border-2 border-violet-300 rounded-lg flex items-center justify-center bg-violet-50">
                <div class="flex flex-wrap gap-1 items-center justify-center">
                  <div v-for="i in TARGET_CARD.number" :key="i"
                       v-html="getShape(TARGET_CARD.shape, TARGET_CARD.color)"></div>
                </div>
              </div>
            </div>
            <div class="text-slate-400">→</div>
            <div class="text-center">
              <div class="text-sm text-slate-600 mb-2">{{ t('conceptFormation.ruleExampleColor') }}</div>
              <div class="text-xs text-green-600">{{ t('conceptFormation.selectRedCard') }}</div>
            </div>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-violet-50 to-violet-100 rounded-xl border border-violet-200">
            <div class="text-2xl font-bold text-violet-700 mb-1">{{ TRIALS_TO_COMPLETE }}</div>
            <div class="text-sm text-violet-700">{{ t('conceptFormation.trials') }}</div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
            <div class="text-2xl font-bold text-purple-700 mb-1">3</div>
            <div class="text-sm text-purple-700">{{ t('conceptFormation.ruleTypes') }}</div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-violet-50 to-purple-50 rounded-xl border border-violet-200">
            <div class="text-2xl font-bold text-slate-600 mb-1">{{ Math.floor(timeLeft / 60) }}</div>
            <div class="text-sm text-slate-700">{{ t('conceptFormation.timeLimitMinutes') }}</div>
          </div>
        </div>

        <Button
          class="w-full bg-gradient-to-r from-violet-700 to-purple-600 hover:from-violet-800 hover:to-purple-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleStartTest"
        >
          {{ t('conceptFormation.startButton') }}
        </Button>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="stage === 'test' && trials[0]" class="max-w-4xl mx-auto space-y-6">
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4">
        <Badge class="bg-violet-100 text-violet-700 border-violet-300" variant="outline">
          {{ t('conceptFormation.trialProgress') }} {{ currentTrialIndex + 1 }} / {{ TRIALS_TO_COMPLETE }}
        </Badge>
        <Badge class="bg-purple-100 text-purple-700 border-purple-300" variant="outline">
          {{ t('conceptFormation.consecutiveCorrect') }} {{ consecutiveCorrect }}
        </Badge>
        <Badge class="bg-blue-100 text-blue-700 border-blue-300" variant="outline">
          {{ t('conceptFormation.ruleChanges') }} {{ ruleChanges.length }}
        </Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4"/>
          <span class="font-semibold">{{ score }}</span>
        </div>
      </div>

      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500"/>
        <span :class="['font-mono text-lg font-bold', timeLeft <= 120 ? 'text-red-500' : 'text-slate-700']">
          {{ Math.floor(timeLeft / 60) }}:{{ (timeLeft % 60).toString().padStart(2, '0') }}
        </span>
      </div>
    </div>

    <Progress :model-value="progress" class="h-2"/>

    <Card class="bg-gradient-to-r from-violet-50 to-purple-50 border-violet-200">
      <CardContent class="py-4">
        <div class="text-center">
          <h3 class="text-lg font-semibold text-violet-800">
            {{ t('conceptFormation.testInstruction') }}
          </h3>
          <p v-if="consecutiveCorrect >= 5" class="text-sm text-orange-600 mt-1">
            <RotateCcw class="w-4 h-4 inline mr-1"/>
            {{ t('conceptFormation.ruleChangeWarning') }}
          </p>
        </div>
      </CardContent>
    </Card>

    <Card class="bg-white/90 backdrop-blur-sm border-violet-200 shadow-lg">
      <CardContent class="py-8">
        <div class="space-y-8">
          <div class="text-center">
            <h4 class="text-lg font-semibold text-slate-700 mb-4">{{ t('conceptFormation.targetCard') }}</h4>
            <div class="flex justify-center">
              <div
                class="w-20 h-20 border-2 border-violet-300 rounded-lg flex items-center justify-center bg-violet-50">
                <div class="flex flex-wrap gap-1 items-center justify-center">
                  <div v-for="i in TARGET_CARD.number" :key="i"
                       v-html="getShape(TARGET_CARD.shape, TARGET_CARD.color)"></div>
                </div>
              </div>
            </div>
          </div>

          <div class="text-center">
            <h4 class="text-lg font-semibold text-slate-700 mb-4">{{ t('conceptFormation.selectMatchingCard') }}</h4>
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 justify-items-center">
              <Button
                v-for="(card, index) in trials[0].cards"
                :key="card.id"
                class="w-32 h-32 p-4 border-2 hover:border-violet-400 hover:bg-violet-50 transition-all duration-200"
                variant="outline"
                @click="() => handleCardSelect(index)"
              >
                <div class="flex flex-wrap gap-1 items-center justify-center">
                  <div v-for="i in card.number" :key="i" v-html="getShape(card.shape, card.color)"></div>
                </div>
              </Button>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>

    <Transition name="slide-fade">
      <div v-if="showFeedback" class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50">
        <Card :class="['border-0 shadow-lg', feedbackCorrect ? 'bg-green-500 text-white' : 'bg-red-500 text-white']">
          <CardContent class="py-3 px-6">
            <div class="flex items-center gap-3">
              <CheckCircle v-if="feedbackCorrect" class="w-5 h-5"/>
              <XCircle v-else class="w-5 h-5"/>
              <span class="font-semibold">
                            {{ feedbackCorrect ? t('conceptFormation.correct') : t('conceptFormation.incorrect') }}
                        </span>
            </div>
          </CardContent>
        </Card>
      </div>
    </Transition>
  </div>

  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-violet-200 shadow-xl">
      <CardHeader class="text-center pb-6">
        <div
          class="w-20 h-20 bg-gradient-to-br from-violet-700 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
          <Trophy class="w-10 h-10 text-white"/>
        </div>

        <CardTitle class="text-3xl text-slate-800 mb-2">{{ t('conceptFormation.testComplete') }}</CardTitle>
        <div class="text-6xl font-bold bg-gradient-to-r from-violet-700 to-purple-600 bg-clip-text text-transparent">
          {{ finalResult.finalScore }}
        </div>
        <p class="text-slate-600">{{ t('conceptFormation.scoreTitle') }}</p>
      </CardHeader>

      <CardContent class="space-y-6">
        <div class="grid grid-cols-2 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-violet-50 to-violet-100 rounded-xl border border-violet-200">
            <div class="text-2xl font-bold text-violet-700 mb-1">{{ finalResult.ruleChangeSuccess }}</div>
            <div class="text-sm text-violet-700">{{ t('conceptFormation.successfulRuleChanges') }}</div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
            <div class="text-2xl font-bold text-purple-700 mb-1">{{ finalResult.overallAccuracy }}%</div>
            <div class="text-sm text-purple-700">{{ t('conceptFormation.overallAccuracy') }}</div>
          </div>
        </div>

        <div class="space-y-3">
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
            <span class="text-slate-600">{{ t('conceptFormation.conceptualFlexibility') }}</span>
            <span class="font-semibold text-slate-800">{{
                Math.round((finalResult.ruleChangeSuccess / 3) * 100)
              }}%</span>
          </div>
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
            <span class="text-slate-600">{{ t('conceptFormation.perseverativeErrors') }}</span>
            <span class="font-semibold text-slate-800">{{ finalResult.perseverativeErrors }}</span>
          </div>
          <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
            <span class="text-slate-600">{{ t('conceptFormation.trialsCompleted') }}</span>
            <span class="font-semibold text-slate-800">{{ finalResult.totalTrials }}</span>
          </div>
        </div>

        <Button
          class="w-full bg-gradient-to-r from-violet-700 to-purple-600 hover:from-violet-800 hover:to-purple-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleComplete"
        >
          {{ t('conceptFormation.viewDetails') }}
        </Button>
      </CardContent>
    </Card>
  </div>
</template>

<style scoped>
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}
</style>
